package com.hjy.attendance.exception;

import com.hjy.attendance.entity.ResultVO;
import com.hjy.attendance.formatter.CustomDateFormatter;
import com.hjy.attendance.response.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @program: home-server
 * @description: 全局异常处理
 * @author: xjr
 * @create: 2020-02-27 20:53
 **/
@ControllerAdvice
@Slf4j
public class ExceptionResolver {

    /**
     * 应用到所有@RequestMapping注解方法，在其执行之前初始化数据绑定器
     *
     * @param binder
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.addCustomFormatter(new CustomDateFormatter());
    }


    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResultVO responseError(Exception e){
        return ResultVO.failure("500",e.toString());
    }

    @ExceptionHandler(ApiException.class)
    @ResponseBody
    public ResultVO responseError(ApiException e){
        return ResultVO.failure(e.getResultEnum().getCode(),e.getMessage());
    }

    @ExceptionHandler(DuplicateKeyException.class)
    @ResponseBody
    public ResultVO<DuplicateKeyException> sqlException(DuplicateKeyException e){
        return ResultVO.failure("500",e.getMessage());
    }
}
